//
//  BLEConnectClouldVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/2.
//

#import "BLEConnectClouldVC.h"
#import "RHCustomTimer.h"
#import <YYAnimatedImageView.h>
#import <YYImage/YYImage.h>
#import "CBLECenterMnger.h"
#import "CBLECenterMnger.h"
#import "CBLEDataParse.h"
#import "BLESetSecretVC.h"
#import "BLESetWifiInputController.h"
#import "RHLocalSettingTypeModel.h"

@interface BLEConnectClouldVC ()
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) NSInteger count;

@property (nonatomic, strong) QMUILabel *stateLab;

@property (nonatomic, strong) QMUILabel *tipsLab;

@property (nonatomic, strong) YYAnimatedImageView  *gifImg;

@property (nonatomic, strong) UIImageView *finishImg;

@property (nonatomic, strong) QMUIButton *finishBtn;
@end

@implementation BLEConnectClouldVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"连接云服务".rh_localized;
    [self setupUI];
    [self createCmd];
    self.timer = [RHCustomTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countAction) userInfo:nil repeats:YES];
}



-(void)createCmd
{
    NSDictionary *cmdDic = @{
        @"field":@"Ems_WifiCnctSt",
        @"regAddr":@(22),
        @"bitWidth":@(2),
        @"offset":@(0),
        @"isBit":@(1),
        @"cmdType":@(LocalSettingType_EMS)
    };
   
    RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:cmdDic];
    self.cmdArray = @[settingModel];
}

-(void)getConnectStatus
{
    [[RHBleCmdManager shareMnger] readDeviceInfoWithCmdModel:[self.cmdArray firstObject]];
    
}


-(void)receiveDeviceMsg:(NSNotification*)no
{
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;
    if (!self.recieveMsg) return;
    NSLog(@"------>收到设备信息:%@",dic);
    RHLocalSettingModel *cmdModel = [self.cmdArray firstObject];
   
    if(cmdModel.regAddr == [dic[CMD_ADDRESS] integerValue]){
        
        NSData *data = dic[CMD_ADDRESS_VALUE];
        NSString *parse_content = [CBLEDataParse parseData:data settingModel:cmdModel];
        NSLog(@"---->%@ = %@",cmdModel.field,parse_content);
       
        //未连网
        if([parse_content integerValue] == 0){
            
        }
        
        //连接上路由
        if([parse_content integerValue] == 1){
           
        }
        
        //连接上云平台
        if([parse_content integerValue] == 2){
            
            [self.timer invalidate];
            self.timer = nil;
            self.gifImg.image = [UIImage imageNamed:@"ble_connect3"];
            [self.finishBtn setTitle:@"完成".rh_localized forState:UIControlStateNormal];
            self.finishBtn.hidden = NO;
            self.stateLab.text = @"设备连接云服务成功".rh_localized;
            self.tipsLab.hidden = YES;
            self.finishImg.hidden = NO;
        }
    }
           
}

-(void)countAction
{
    if(self.count == 100){
        [self.timer invalidate];
        self.timer = nil;
        [self.gifImg stopAnimating];
        self.gifImg.image = [UIImage imageNamed:@"ble_connect3"];
        [QMUITips showError:@"连接超时".rh_localized];
        self.stateLab.text = @"连接超时".rh_localized;
        [self.finishBtn setTitle:@"重试".rh_localized forState:UIControlStateNormal];
        self.finishBtn.hidden = NO;
        return;
    }
    self.count += 1;
    self.stateLab.text = [NSString stringWithFormat:@"%@(%ld%%)",@"设备正在连接云服务...".rh_localized,self.count];
    [self getConnectStatus];
}

- (void)setupUI{
    kWeakSelf;
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.backgroundColor = CFTabViewBgColor;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *contentView = kView;
    contentView.backgroundColor = CFTabViewBgColor;
    [scrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.offset(kUI_WINDOW_W);
        make.height.offset(kUI_WINDOW_H - kNavHeight);
    }];
    
    UIImageView *stepImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_config_step3"]];
    stepImg.contentMode = UIViewContentModeScaleAspectFit;
    [contentView addSubview:stepImg];
    [stepImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.width.offset(kScaleW(120));
        make.height.offset(40);
        make.centerX.mas_offset(0);
    }];

    
    
    
    _gifImg = [[YYAnimatedImageView alloc]initWithImage:[YYImage imageNamed:@"ble_connect_cloud.gif"]];
    [contentView addSubview:_gifImg];
    [_gifImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(kScaleW(279));
        make.height.offset(kScaleW(236));
        make.centerX.mas_offset(0);
        make.top.equalTo(stepImg.mas_bottom).offset(30);
    }];
    
    QMUILabel *stateLab = [[QMUILabel alloc]init];
    stateLab.text = @"设备正在连接云服务...".rh_localized;
    stateLab.textColor = kRGB(63, 68, 67);
    stateLab.font = kSYSTEMFONT(16);
    stateLab.numberOfLines = 0;
    stateLab.textAlignment = NSTextAlignmentCenter;
    [contentView addSubview:stateLab];
    self.stateLab = stateLab;
    [stateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(weakSelf.gifImg.mas_bottom).offset(70);
    }];
    
    QMUILabel *tipsLab = [[QMUILabel alloc]init];
    tipsLab.text = @"整个联网过程中，请保持设备电量充足，保证路由器网络正常".rh_localized;
    tipsLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    tipsLab.font = kSYSTEMFONT(12);
    tipsLab.textAlignment = NSTextAlignmentCenter;
    tipsLab.numberOfLines = 0;
    [contentView addSubview:tipsLab];
    self.tipsLab = tipsLab;
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(stateLab.mas_bottom).offset(15);
    }];
    
    _finishImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_connect_success"]];
    _finishImg.contentMode = UIViewContentModeScaleAspectFit;
    [contentView addSubview:_finishImg];
    [_finishImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.stateLab.mas_top).offset(-10);
        make.width.mas_offset(kScaleW(40));
        make.height.mas_offset(kScaleW(40));
        make.centerX.mas_offset(0);
    }];
    _finishImg.hidden = YES;
    
    QMUIButton *finishBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [finishBtn setFrame:CGRectMake(0, 0, 204, 45)];
    [finishBtn setBackgroundColor:UIColor.blackColor];
    [finishBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [finishBtn setTitle:@"完成".rh_localized forState:UIControlStateNormal];
    [finishBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [finishBtn.layer setCornerRadius:8];
    [finishBtn setGradientBackgroundWithColors:@[kRGB(106, 215, 133),kRGB(94, 203, 183)] locations:@[@(0),@(1)] startPoint:CGPointMake(0, 0.5) endPoint:CGPointMake(1, 0.5)];
    [contentView addSubview:finishBtn];
    finishBtn.hidden = YES;
    self.finishBtn = finishBtn;
    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-20);
    }];
    
    [[finishBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof QMUIButton * _Nullable button) {
        if ([button.titleLabel.text isEqualToString:@"完成".rh_localized]) {
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }
        if ([button.titleLabel.text isEqualToString:@"重试".rh_localized]) {
            for (UIViewController *vc in weakSelf.navigationController.viewControllers) {
                if([vc isKindOfClass:[BLESetWifiInputController class]]){
                    [weakSelf.navigationController popToViewController:vc animated:YES];
                }
            }
            
        }
    }];
}



-(void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
}


@end
